package com.dlts.freemarker.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dlts.freemarker.entity.Tables;
import com.dlts.freemarker.mapper.TableMapper;
import com.dlts.freemarker.model.table.*;
import com.dlts.freemarker.service.TablesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author DLTS
 * @since 2022-01-11
 */
@Slf4j
@Service
public class TablesServiceImpl extends ServiceImpl<TableMapper, Tables> implements TablesService {

    // 库名
    @Value("${spring.datasource.database}")
    private String database;

    @Override
    public IPage<TablesPageQueryVO> pageQuery(TablesPageQueryDTO dto) {
        return page(new Page<>(dto.getCurrent(), dto.getSize()), Wrappers.lambdaQuery(Tables.class)
                .eq(Tables::getTableSchema, database)
                .like(StringUtils.isNotBlank(dto.getTableName()), Tables::getTableName, dto.getTableName())
                .select(Tables::getTableName, Tables::getAutoIncrement, Tables::getEngine, Tables::getTableComment, Tables::getCreateTime))
                .convert(c -> BeanUtil.copyProperties(c, TablesPageQueryVO.class));
    }

    @Override
    public TablesDetailVO detail(TablesDetailDTO dto) {
        return null;
    }

    @Override
    public List<TableSelectorVO> selector() {
        return list(Wrappers.lambdaQuery(Tables.class)
                .eq(Tables::getTableSchema, database).select(Tables::getTableName, Tables::getTableComment))
                .stream().map(tables -> BeanUtil.copyProperties(tables, TableSelectorVO.class)).collect(Collectors.toList());
    }
}
